package com.systemutils;

import android.app.Activity;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import com.dialogutils.ToastUtil;

import java.util.ArrayList;

/**
 * 日期：2019年3月16日
 * 公司：北京子杰宝贝科技有限公司
 * 地址：北京市朝阳区朝阳农场
 * 开发者：达选文
 * <p>
 * 主体功能：底层权限帮助类
 */
public class PermissionHelper {
    public static int REQUEST_CODE=123;
    private static PermissionHelper mPerHelper;
    private int callBackCode;

    public static PermissionHelper getInstance() {
        if (mPerHelper == null) {
            mPerHelper = new PermissionHelper();
        }
        return mPerHelper;
    }

    /**
     * 请求权限
     *
     * @param permission   权限名字
     * @param callBackCode 回调code
     */
    public PermissionHelper requestPermissions(Activity mActivity,PermissionIml permissionIml,String[] permission, int callBackCode) {
        this.callBackCode = callBackCode;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { // Android 6.0判断，6.0以下跳过。在清单文件注册即可，不用动态请求，这里直接视为有权限
            ArrayList<String> toApplyList = new ArrayList<String>();
            for (String perm : permission) {
                if (PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(mActivity, perm)) {
                    toApplyList.add(perm);
                }
            }
            String[] tmpList = new String[toApplyList.size()];
            tmpList=toApplyList.toArray(tmpList);
            permissionIml.callbackPermission(mActivity,tmpList, REQUEST_CODE);
        }
        return this;
    }

    public interface PermissionIml{
        void callbackPermission(Activity activity, String[] list, int requestCode);
    }

    /**
     * 在Activity中的onRequestPermissionsResult中调用,用来接收结果判断
     *
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    public PermissionHelper checkPermissionsResult(Activity mActivity, int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == callBackCode) {
            for (int result : grantResults) {
                if (result == PackageManager.PERMISSION_GRANTED) {
                    ToastUtil.showShort(mActivity, "权限获取成功");
                } else {
                    ToastUtil.showShort(mActivity, "权限获取失败");
                }
            }
        }
        return this;
    }

    /**
     * 销毁
     */
    public void destroyHelper(){
        if(mPerHelper!=null){
            mPerHelper=null;
        }
    }
}